//
//  MYCustomEmojiView.m
//  JQLive
//
//  Created by Bruce on 2020/6/9.
//  Copyright © 2020 JQLive. All rights reserved.
//

#import "MYCustomEmojiView.h"

//将数字转为
//将数字转为
#define EMOJI_CODE_TO_SYMBOL(x) ((((0x808080F0 | (x & 0x3F000) >> 4) | (x & 0xFC0) << 10) | (x & 0x1C0000) << 18) | (x & 0x3F) << 24);

@interface MYCustomEmojiView () <UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>
@property(nonatomic, strong) UIPageControl *pageControlBottom;
// 一行中 cell的个数
@property (nonatomic) NSUInteger itemCountPerRow;
// 一页显示多少行
@property (nonatomic) NSUInteger rowCount;
@end
@implementation MYCustomEmojiView
{
    NSArray *emojiArray;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = UIColorMakeWithHex(@"#f5f5f6");
        emojiArray = [self defaultEmoticons];
        [self createUI];
    }
    return self;
}

- (void)createUI {
    self.itemCountPerRow  = 7;
    self.rowCount = 4;
    //为了摆放分页控制器，创建一个背景view
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    [self addSubview:bgView];
  //分页控制器
  _pageControlBottom = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
  [bgView addSubview:_pageControlBottom];
    
    //collectionView布局
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    //水平布局
    layout.scrollDirection=UICollectionViewScrollDirectionHorizontal;
    //设置每个表情按钮的大小为30*30
    layout.itemSize=CGSizeMake(30, 30);
    
    
    CGFloat row = self.itemCountPerRow;
    CGFloat line = self.rowCount;
    CGFloat padding = (SCREEN_WIDTH - row * 30)/row;
    //设置行列间距
    layout.minimumLineSpacing= padding;
    layout.minimumInteritemSpacing= 10;
    //计算每个分区的左右边距
    CGFloat sectionOffset = padding / 2;
    //设置分区的内容偏移
    layout.sectionInset=UIEdgeInsetsMake(10, sectionOffset, 10, sectionOffset);
    CGFloat height = 15*line + 30*line + 10*2;
    UICollectionView *scrollView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, height) collectionViewLayout:layout];
    //打开分页效果
    scrollView.pagingEnabled = YES;
    
    [scrollView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"emojiCell"];

    scrollView.delegate=self;
    scrollView.dataSource=self;
    scrollView.backgroundColor = bgView.backgroundColor;
    [bgView addSubview:scrollView];
    
    
}
//每页28个表情
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    long count = self.rowCount *self.itemCountPerRow;
    int page =(int) emojiArray.count/count + (emojiArray.count%count>0?1:0);
    DLog(@"page = %d,coun = %ld",page,emojiArray.count);
    return page*self.rowCount *self.itemCountPerRow;
   
}
//返回页数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
     static NSString *identifier = @"emojiCell";
       UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
       if (!cell) {
           cell = [[UICollectionViewCell alloc]init];
       }
       
    NSUInteger item = indexPath.item;
    NSUInteger x;
    NSUInteger y;
    [self targetPositionWithItem:item resultX:&x resultY:&y];
    NSUInteger item2 = [self originItemAtX:x y:y];
    DLog(@" index.row = %ld item = %ld,x=%ld y= %ld",indexPath.item,item2,x,y);
    [self setCell:cell withIndexPath:item2];
       
       return cell;
}
- (void)setCell:(UICollectionViewCell *)cell withIndexPath:(NSUInteger)item {
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UILabel *emojiLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    if (item <emojiArray.count ) {
        emojiLabel.text = emojiArray[item];
    }
    else
    {
        emojiLabel.text = @"";
    }
    emojiLabel.font = [UIFont systemFontOfSize:25];
    [cell.contentView addSubview:emojiLabel];
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSUInteger item = indexPath.item;
    NSUInteger x;
    NSUInteger y;
    [self targetPositionWithItem:item resultX:&x resultY:&y];
    NSUInteger item2 = [self originItemAtX:x y:y];
    if (item2 >= emojiArray.count ) {
        return;
    }
    NSString * emojiStr = emojiArray[item2];
   
    //这里手动将表情符号添加到textField上
    //NSLog(@"表情 %@", emojiStr);
    if (self.delegate && [self.delegate respondsToSelector:@selector(didClickEmojiLabel:)]) {
        [self.delegate didClickEmojiLabel:emojiStr];
    }
    
}
//翻页后对分页控制器进行更新
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat contenOffset = scrollView.contentOffset.x;
    int page = contenOffset/scrollView.frame.size.width+((int)contenOffset%(int)scrollView.frame.size.width==0?0:1);
    _pageControlBottom.currentPage = page;

}



//发送表情
- (void)sendEmoji {
    if (self.delegate && [self.delegate respondsToSelector:@selector(didClickSendEmojiBtn)]) {
        [self.delegate didClickSendEmojiBtn];
    }
}

//表情包
- (NSArray *)defaultEmoticons {
    NSMutableArray *array = [NSMutableArray new];
    for (int i = 0x1F600; i <= 0x1F64F; i++) {
        if (i < 0x1F641 || i > 0x1F644) {
            int sym = EMOJI_CODE_TO_SYMBOL(i);
            NSString *emoT = [[NSString alloc] initWithBytes:&sym length:sizeof(sym) encoding:NSUTF8StringEncoding];
            [array addObject:emoT];
        }
    }
    return array;
   
}

#pragma mark - 计算位置上的数据
// 根据 item 计算目标item的位置
// x 横向偏移  y 竖向偏移
- (void)targetPositionWithItem:(NSUInteger)item
                       resultX:(NSUInteger *)x
                       resultY:(NSUInteger *)y
{
    NSUInteger page = item/(self.itemCountPerRow*self.rowCount);
//    int page =(int) item/count + (eojiArray.count%count>0?1:0);

    NSUInteger theX = item / self.rowCount - page * self.itemCountPerRow;
    NSUInteger theY = item % self.rowCount +  page * self.rowCount;
    if (x != NULL) {
        *x = theX;
    }
    if (y != NULL) {
        *y = theY;
    }
}

// 根据偏移量计算item
- (NSUInteger)originItemAtX:(NSUInteger)x
                          y:(NSUInteger)y
{
    NSUInteger item = x  + y*self.itemCountPerRow;
    return item;
}

@end
